package com.aigc.sclassroom.service.impl;

import com.aigc.sclassroom.mapper.CourseMapper;
import com.aigc.sclassroom.pojo.Course;
import com.aigc.sclassroom.pojo.Result;
import com.aigc.sclassroom.pojo.Team;
import com.aigc.sclassroom.pojo.upStudent;
import com.aigc.sclassroom.service.CourseService;
import com.aigc.sclassroom.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;


@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;

    @Override

    public List<Course> list() {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        Long userId =(id.longValue());
        return courseMapper.findByUserId(userId);
    }
    @Override
    public Course getCourseDetail(Long courseManageId) {
        return courseMapper.getCourseDetail(courseManageId);
    }

    @Override
    public List<Team> listTeam(Long courseManageId) {
        return courseMapper.findByCourseManageId(courseManageId);
    }

    @Override
    public void deleteStudent(Long teamId) {courseMapper.deleteByTeamId(teamId);
    }

    @Override
    public void addStudent(Long userId, Long courseManageId) {
        courseMapper.addStudent(userId,courseManageId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result uploadStudentFile(List<upStudent> students) {
        //将文件中读到的数据存到街镇实体类中

        for (upStudent student : students) {
            Long teamUserId = student.getTeamUserId();
            Long courseManageId = student.getCourseManageId();
            if (teamUserId == null) {
                return Result.error("学号不能为空");
            }
            if (courseManageId == null) {
                return Result.error("排课id不能为空");
            }
            try {
                courseMapper.addStudent(student.getTeamUserId(),student.getCourseManageId());
            }catch (DataAccessException e){
                return Result.error("该课程已存在该学生(不能重复插入) || 用户不存在或课程不存在");
            }
        }
        return Result.success("批量导入学生成功");
    }


}
